// pages/user/special/join/join.js
const config = getApp().globalData.config
const T = getApp().globalData.T
let token = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: -1, // 专场id
    page: 1,
    size: 10,
    list: [],
    isLoaded: false,
    isFirstTip: true,
    imageIcon: ['/resource/image/checkbox_normal.png', '/resource/image/checkbox_selected.png'],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.data.id = Number(options.id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    token = getApp().globalData.token;
    this.getDetail();
  },

  getDetail() {
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'special_activity/company_usable_position',
      method: 'GET',
      data: {
        id: this.data.id,
        token: token,
        page: this.data.page,
        size: this.data.size
      },
      success: (res) => {
        if (res.rowCount == this.data.list.length) {
          this.data.isLoaded = true;
          return
        }
        let _list = JSON.parse(JSON.stringify(res.list));
        _list.map(m => {
          m.selected = false;
        })
        this.setData({
          list: this.data.list.concat(res.list)
        })
      }
    })
  },

  onReachBottom: function() {
    if (this.data.isLoaded) {
      if (this.data.isFirstTip) {
        T.toast({
          id: '#toast',
          text: '已加载完全部数据了'
        });
      }
      this.data.isFirstTip = false;
      return;
    }
    this.data.page += 1;
    this.getDetail();
  },

  onSelectPositon(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      [`list[${index}].selected`]: !this.data.list[index].selected,
    })
  },

  onSubmit() {
    let list = [];
    this.data.list.forEach(m => {
      if (m.selected) {
        list.push(m.id);
      }
    });
    console.log(list);
    let param = {
      token: token,
      specialActivityId: this.data.id,
      positionIds: list
    }
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'special_activity/join_special_acivity?' + T.param(param),
      method: 'POST',
      success: (res) => {
        T.toast({ id: '#toast', text: '操作成功', success: () => {
          wx.navigateBack({
            delta: 1
          })
        } });
      }
    })

  }

})